<template>
  <div class="map-container">
    <Search
      placeholderStr="搜索城市"
      :root-style="rootStyle"
      @input="handleInput"
      :value="keyword"
      @confirm="searchConfirm"
    ></Search>

    <div class="city-list">
      热门:
      <div class="list-wrap">
        <div
          class="city"
          v-for="(item, index) in fireWordList"
          :key="index"
          @click="searchWord(item)"
        >
          {{ item.name }}
        </div>
      </div>
    </div>

    <map
      id="waterMap"
      class="map"
      :longitude="longitude"
      :latitude="latitude"
      :scale="scale"
      layer-style="1"
      :markers="cornerMarkerList"
      :circles="circles"
      :min-scale="4"
      :max-scale="18"
      @markertap="tapMap"
      @callouttap="tapMap"
      @tap="clickMap"
      @regionchange="onChangeRegion"
      @updated="hideLoading"
    ></map>

    <view class="hover-btn" @click="goCellList" v-if="preScale >= 13">
      <img src="https://fh4.qinyuan.cn/uploads/view/static/cell-icon.png" class="icon" />
      <view class="text">周边小区</view>
    </view>

    <view class="hover-btn" style="bottom: 426rpx" @click="isShowGuide = true">
      <view class="text" style="font-weight: bold; font-size: 54rpx">?</view>
    </view>

    <Privacy ref="privacy"></Privacy>

    <view class="flower" v-if="modalData.id != undefined">
      <div class="info">
        <div class="flower-name">{{ modalData.buildingname }}</div>
        <div class="flower-address">{{ modalData.area }}</div>
        <div class="btn-wrap">
          <div class="example">全屋方案案例：{{ modalData.casenum }}户</div>
          <div class="detail" @click="viewDetail(modalData)">查看详情</div>
        </div>
      </div>
      <img src="https://fh4.qinyuan.cn/uploads/view/static/house-123.png" class="house-img" />
    </view>

    <view v-if="isShowGuide" class="map-mask">
      <view class="title">沁园足迹指引助手</view>
      <view class="sub-title">1.缩放地图到区域</view>
      <img src="../../static/step1.png" class="step-img" />
      <view class="sub-title">2.点击地图上地标记点</view>
      <img src="../../static/step2.png" class="step-img" />
      <view class="sub-title">3.查看底部案例详情</view>
      <img src="../../static/step3.png" class="step-img" />
      <view class="know-btn" @click="isShowGuide = false">知道了</view>
    </view>
  </div>
</template>

<script>
import Privacy from '../../components/Privacy/Privacy.vue';
const QQMapWX = require('../../static/qqmap-wx-jssdk.js');
import requestV1 from '../../common/requestV1';
import Search from '../../components/Search/Search.vue';
export default {
  components: {
    Search,
    Privacy
  },
  data() {
    return {
      rootStyle: {
        width: 'calc(100% - 72rpx)',
        margin: '0 auto',
        borderRadius: '12rpx'
      },
      longitude: '121.266868',
      latitude: '31.219817',
      scale: 12,
      markers: [], // 地图标记
      circles: [], // 圆
      modalData: {}, // 标记详情
      cornerLocation: {
        x0: 0,
        x1: 0,
        y0: 0,
        y1: 0
      }, // 四个角的经纬度
      qqMapSdk: null,
      activeMarker: null,
      keyword: '',
      fireWordList: [],
      isInit: false,
      timer: null,
      getMapDataTimer: null,
      mapContext: null,
      preScale: 12,
      interTimer: null,
      isShowText: false,
      isShowGuide: false
    };
  },
  computed: {
    cornerMarkerList() {
      const { x0, x1, y0, y1 } = this.cornerLocation;
      const isInnerViews = ({ longitude, latitude }) => {
        return longitude >= x0 && longitude <= x1 && latitude >= y0 && latitude <= y1;
      };
      const cornerMarkerList = this.markers.filter(isInnerViews);
      console.log(
        `this.cornerMarkerList`,
        this.cornerLocation,
        this.markers,
        cornerMarkerList.length,
        this.markers.length
      );
      return cornerMarkerList;
    }
  },
  onLoad() {
    this.qqMapSdk = new QQMapWX({
      // key: 'R5GBZ-UYF6V-XT7P6-5G2WP-GSIPV-2HBU4'
      key: 'D4RBZ-HCPKV-L2HPT-5BX24-TKWH6-4KF3X'
    });
    this.mapContext = uni.createMapContext('waterMap', this);
    console.log(this.mapContext, 'this.mapContext');
    this.getScale();
    this.listenScale();
  },
  onReady() {
    uni.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation']) {
          // 授权成功
          console.log(`getSetting scope.userLocation`);
          this.getLocation();
        } else {
          // 没有授权的话检查是否进入过
          wx.getStorage({
            key: 'isJoined',
            success: (res) => {
              console.log(res, 'res');
              if (res.data) {
                this.getLocation();
              } else {
                // 未授权过
                this.$refs.privacy.open().then((res) => {
                  if (res.confirm) {
                    this.getLocation();
                  } else {
                    uni.navigateBack();
                  }
                });
                // 表示不是第一次进入
                wx.setStorage({
                  key: 'isJoined',
                  data: true,
                  success(res) {
                    console.log(res);
                  }
                });
              }
            },
            fail: (err) => {
              this.$refs.privacy.open().then((res) => {
                if (res.confirm) {
                  this.getLocation();
                } else {
                  uni.navigateBack();
                }
              });
              // 表示不是第一次进入
              wx.setStorage({
                key: 'isFirstJoin',
                data: true,
                success(res) {
                  console.log(res);
                }
              });
            }
          });
        }
      }
    });

    this.fireWords();
  },
  onUnload() {
    clearInterval(this.interTimer);
  },
  methods: {
    hideLoading() {
      console.log('hide loading');
      uni.hideLoading();
    },
    getScale(cb) {
      const _this = this;
      this.mapContext.getScale({
        success: (res) => {
          // console.log(res, 'get scale success')
          _this.isShowText = res.scale >= 8;
          cb && cb(res.scale);
        }
      });
    },
    getLocation() {
      wx.getLocation({
        type: 'wgs84',
        success: (res) => {
          this.latitude = res.latitude;
          this.longitude = res.longitude;
          this.getMapData(true);
          this.getCornerLocation();
        },
        fail: (err) => {
          this.scale = 4;
          this.preScale = 4;
          // 拒绝授权也需要获取标记信息
          this.getMapData(true);
          this.getCornerLocation();
        }
      });
    },
    handleInput(e) {
      this.keyword = e;
    },
    searchWord(data) {
      this.searchConfirm(data.name);
      // setTimeout(() => {
      //   this.keyword = data.name
      // }, 300)
    },
    async searchConfirm(value) {
      this.keyword = value;
      if (this.keyword) {
        // 现根据 keyword 获取搜索的 位置信息
        const locationRes = await requestV1({
          url: '/casemarks/map_search',
          method: 'post',
          data: {
            keyword: this.keyword
          }
        });
        console.log(locationRes, '===locationRes===')
        this.longitude = +locationRes.data.lng_lat.split(',')[1];
        this.latitude = +locationRes.data.lng_lat.split(',')[0];
        this.scale = +locationRes.data.ratio;
        this.preScale = this.scale;
        const data = await requestV1({
          url: '/casemarks/search',
          method: 'post',
          data: {
            keyword: this.keyword
          }
        });
        this.markers = data.data.map((m, index) => ({
          ...m,
          iconPath: '../../static/location-icon.png',
          id: index,
          dataId: m.id,
          width: 22,
          height: 35,
          latitude: m.latitude,
          longitude: m.longitude,
          callout: {
            content: index + 1,
            color: '#000',
            fontSize: 12,
            bgColor: 'transparent',
            padding: 5,
            display: 'ALWAYS',
            textAlign: 'center',
            anchorY: 28
          }
        }));
      } else {
        this.getMapData();
      }
    },
    listenScale() {
      this.interTimer = setInterval(() => {
        this.getScale(async (scale) => {
          if (Math.floor(scale) != this.preScale) {
            // 地图被缩放且当前小于11
            if (this.preScale <= 11) {
              this.keyword = ''
            }
            if (this.keyword) {
              this.preScale = Math.floor(scale);
              const data = await requestV1({
                url: '/casemarks/search',
                method: 'post',
                data: {
                  keyword: this.keyword
                }
              });
              data.data = data.data.slice(0, 2000);
              this.markers = data.data.map((m, index) => ({
                ...m,
                iconPath: '../../static/location-icon.png',
                id: index,
                dataId: m.id,
                width: 22,
                height: 35,
                latitude: m.latitude,
                longitude: m.longitude,
                callout: {
                  content: index + 1,
                  color: '#000',
                  fontSize: 12,
                  bgColor: 'transparent',
                  padding: 5,
                  display: 'ALWAYS',
                  textAlign: 'center',
                  anchorY: 28
                }
              }));
              clearTimeout(this.timer);
            } else {
              this.preScale = Math.floor(scale);
              this.getMapDataDebounce();
            }
          }
        });
      }, 1000);
    },
    getMapDataDebounce() {
      if (this.getMapDataTimer) {
        clearTimeout(this.getMapDataTimer);
      }
      this.getMapDataTimer = setTimeout(() => {
        this.getMapData();
      }, 500);
    },
    onChangeRegion(e) {
      this.keyword = ''
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(() => {
        this.getCenterLocation();
      }, 500);
    },
    getCenterLocation() {
      this.mapContext.getCenterLocation({
        success: (res) => {
          this.latitude = res.latitude;
          this.longitude = res.longitude;
          this.getCornerLocation();
        }
      });
    },
    async changeRegion(e) {
      if (this.isInit) return;
      if (e.type !== 'end') return;
      if (this.keyword) {
        const data = await requestV1({
          url: '/casemarks/search',
          method: 'post',
          data: {
            keyword: this.keyword
          }
        });
        this.markers = data.data.map((m, index) => ({
          ...m,
          iconPath: '../../static/location-icon.png',
          id: index,
          dataId: m.id,
          width: 22,
          height: 35,
          callout: {
            content: index + 1,
            color: '#000',
            fontSize: 12,
            bgColor: 'transparent',
            padding: 5,
            display: 'ALWAYS',
            textAlign: 'center',
            anchorY: 28
          }
        }));
        clearTimeout(this.timer);
      } else {
        this.latitude = e.detail.centerLocation.latitude;
        this.longitude = e.detail.centerLocation.longitude;
        this.scale = e.detail.scale;
        this.getMapData();
      }
    },
    goCellList() {
      clearInterval(this.interTimer);
      const queryStr = `?latitude=${this.latitude}&longitude=${this.longitude}&ratio=${this.scale}`;
      const url = '/pages/cellList/cellList' + queryStr;
      this.goPage(url);
    },
    viewDetail(data) {
      const queryString = `?buildingname=${data.buildingname}&id=${data.dataId}&latitude=${data.latitude}&longitude=${data.longitude}$ratio=${this.scale}`;
      this.goPage('/pages/exampleList/exampleList' + queryString);
    },
    async fireWords() {
      const data = await requestV1({
        url: '/casemarks/search_word',
        method: 'get'
      });
      this.fireWordList = data.data;
    },
    getMapData(isInit = false) {
      if (this.preScale < 10) {
        this.searchCountProvince();
      } else {
        this.searchMarks(isInit);
      }
    },
    // 获取四角的经纬度信息
    getCornerLocation() {
      let systemInfo = wx.getSystemInfoSync();
      let windowHeight = systemInfo.windowHeight; // 可视窗口高度
      let windowWidth = systemInfo.windowWidth; // 可视窗口宽度
      const _this = this;
      this.mapContext.getRegion({
        success: (res) => {
          this.cornerLocation = {
            x0: res.southwest.longitude,
            x1: res.northeast.longitude,
            y0: res.southwest.latitude,
            y1: res.northeast.latitude
          };
        }
      });
      // this.mapContext.getCenterLocation({
      //   success(res) {
      //     let centerLat = res.latitude;
      //     let centerLng = res.longitude;

      //     // 计算当前缩放级别
      //     _this.mapContext.getScale({
      //       success: function (scaleRes) {
      //         let scale = scaleRes.scale;

      //         // 计算四个角的经纬度
      //         let neLat = centerLat + (windowHeight / 2 / scale) * 0.000008983;
      //         let neLng =
      //           centerLng +
      //           ((windowWidth / 2 / scale) * 0.000008983) / Math.cos(centerLat * 0.01745);
      //         let swLat = centerLat - (windowHeight / 2 / scale) * 0.000008983;
      //         let swLng =
      //           centerLng -
      //           ((windowWidth / 2 / scale) * 0.000008983) / Math.cos(centerLat * 0.01745);

      //         this.cornerLocation = {
      //           swLat,
      //           neLat,
      //           swLng,
      //           neLng
      //         };

      //         console.log('东北角经纬度:', neLat, neLng);
      //         console.log('西南角经纬度:', swLat, swLng);
      //       }
      //     });
      //   }
      // });
    },
    // 根据经纬度检查标记点是否在视口内
    isInViewport(data) {
      return lat >= swLat && lat <= neLat && lng >= swLng && lng <= neLng;
    },
    // 获取粗略分布
    async searchCountProvince() {
      // uni.showLoading({ icon: 'none' });
      setTimeout(() => {
        uni.hideLoading();
      }, 1000);

      if (!this.latitude && !this.longitude) return;

      const data = await requestV1({
        url: '/map/getProvinceCityData',
        method: 'post',
        data: {
          lat_lng: '27.85198530564679,110.26824736136142',
          ratio: this.preScale
        }
      });
      // 粗略分布的圆圈范围
      const radiusMap = {
        14: 12000,
        13: 12000,
        12: 12000,
        11: 12000,
        10: 12000,
        9: 12000,
        8: 20000,
        7: 32000,
        6: 65000,
        5: 110000,
        4: 220000
      };
      // 显示文字距离顶部的距离
      const anchorYMap = {
        10: 55,
        9: 65,
        8: 65,
        7: 65,
        6: 65,
        5: 65,
        4: 65
      };
      // this.circles = data.data.map((m) => {
      //   return {
      //     ...m,
      //     longitude: m.lng_lat.split(',')[1],
      //     latitude: m.lng_lat.split(',')[0],
      //     color: 'rgba(55, 68, 134, 0.8)',
      //     fillColor: 'rgba(1, 28, 97, 0.89)', // 填充颜色
      //     radius: radiusMap[this.preScale], // 圆半径
      //     strokeWidth: 1 // 边
      //   };
      // });

      this.markers = data.data.map((m, index) => ({
        ...m,
        iconPath: '../../static/circle.png',
        longitude: m.lng_lat.split(',')[1],
        latitude: m.lng_lat.split(',')[0],
        id: index,
        dataId: m.id,
        width: 80,
        height: 80,
        anchor: { x: 0.5, y: 0.6 },
        alpha: 0.9,
        callout: {
          // content: `${m.city || m.province}\n${m.count}`,
          content: `${m.count}`,
          color: '#fff',
          fontSize: 16,
          bgColor: 'transparent',
          padding: 5,
          display: 'ALWAYS',
          textAlign: 'center',
          anchorY: anchorYMap[this.preScale] - 5
        }
      }));
      // this.markers = [];
      console.log(data.data, 'data.data');
    },
    async searchMarks(isInit) {
      isInit && (this.isInit = isInit);

      if (!this.latitude && !this.longitude) return;

      // uni.showLoading({ icon: 'none' });
      setTimeout(() => {
        uni.hideLoading();
      }, 1000);
      const data = await requestV1({
        url: '/casemarks/index',
        method: 'post',
        data: {
          lat_lng: `${this.latitude},${this.longitude}`,
          ratio: Math.floor(this.preScale)
        }
      });
      // data.data = data.data.slice(0, 2000)
      this.markers = data.data.map((m, index) => ({
        ...m,
        iconPath: '../../static/location-icon.png',
        id: index,
        dataId: m.id,
        latitude: m.latitude,
        longitude: m.longitude,
        width: 22,
        height: 35,
        // label:{
        // 	content: m.casenum ? m.casenum : '',
        // 	color:'#000000',
        // 	collision: 'poi'
        // },
        callout: {
          content: m.casenum ? m.casenum : '',
          color: '#000',
          fontSize: 12,
          // bgColor: 'transparent',
          // padding: 5,
          display: 'ALWAYS',
          textAlign: 'center',
          anchorY: 25,
          collision: 'poi'
          // 'collision-relation': 'alone',
        }
      }));
      this.circles = [];
      isInit && (this.isInit = false);
      // this.circles = data.data.map(m => ({
      //   ...m,
      //   color: 'rgba(55, 68, 134, 0.29)',
      //   fillColor: 'rgba(55, 68, 134, 0.29)', // 填充颜色
      //   radius: 1200, // 圆半径
      //   strokeWidth: 1 // 边
      // }))
    },
    setCircle(markerId) {
      if (this.preScale < 10) return;
      const markerData = this.markers.find((item) => item.id == markerId);

      // this.circles = [
      //   {
      //     ...markerData,
      //     color: 'rgba(55, 68, 134, 0.29)',
      //     fillColor: 'rgba(1, 28, 97, 0.29)', // 填充颜色
      //     radius: 50, // 圆半径
      //     strokeWidth: 1 // 边
      //   }
      // ];
      this.modalData = markerData;
    },
    clickMap(e) {
      console.log(e, '鼠标点击位置');
    },
    goPage(url, links) {
      url = links ? url + '?url=' + links : url;

      uni.navigateTo({
        url
      });
    },
    tapMap(e) {
      if (this.preScale < 10) return;
      // 将上一个选中的恢复原样
      if (this.activeMarker) {
        this.activeMarker.iconPath = '../../static/location-icon.png';
        this.activeMarker.callout = {
          content: this.activeMarker.callout.content,
          color: '#000',
          fontSize: 12,
          bgColor: 'transparent',
          padding: 5,
          display: 'ALWAYS',
          textAlign: 'center',
          anchorY: 28
        };
      }
      const activeIcon = '../../static/location-active-icon.png';
      const marker = this.markers.find((item) => item.id == e.detail.markerId);
      marker.iconPath = activeIcon;
      marker.callout = {
        content: marker.callout.content,
        color: '#000',
        fontSize: 12,
        bgColor: 'transparent',
        padding: 5,
        display: 'ALWAYS',
        textAlign: 'center',
        anchorY: 26
      };
      this.activeMarker = marker;
      this.setCircle(e.detail.markerId);
    },
    mapclick() {
      var that = this;
      console.log('地图点击');
      wx.chooseLocation({
        success(res) {
          console.log('地图点击事件', res);
        },
        fail(res) {
          console.log('点击地图fail:' + JSON.stringify(res));
        },
        complete(res) {
          // complete
          console.log('点击地图complete:' + JSON.stringify(res));
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.map-mask {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 99;
  text-align: center;
  background-color: rgba(0, 0, 0, 0.5);

  .title {
    color: #fff;
    font-size: 46rpx;
    text-align: center;
    margin-top: 36rpx;
  }

  .sub-title {
    font-size: 42rpx;
    color: #fff;
    margin: 46rpx 0;
  }

  .step-img {
    width: 80%;
    height: 220rpx;
  }

  .know-btn {
    width: 200rpx;
    height: 60rpx;
    line-height: 60rpx;
    font-size: 35rpx;
    text-align: center;
    color: #fff;
    margin: 0 auto;
    background: rgba(255, 255, 255, 0.3);
    border-radius: 10rpx;
    margin-top: 30rpx;
  }
}

.city-list {
  width: calc(100% - 63rpx - 24rpx);
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 24rpx auto 12rpx;

  .list-wrap {
    display: flex;
    overflow: auto;
    width: calc(100% - 84rpx);
  }

  .city {
    min-width: 127.8rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #fff;
    border-radius: 19.8rpx;
    font-size: 31.788rpx;
    margin-right: 12rpx;
  }
}

.flower {
  position: absolute;
  padding: 36rpx 36rpx 30px;
  bottom: 0;
  left: 0;
  right: 0;
  //width: 535rpx;
  border-radius: 20rpx;
  background: #fff;
  display: flex;

  .info {
    width: calc(100% - 174rpx);
    height: 100%;

    .flower-name {
      font-size: 36rpx;
      color: #000;
      font-weight: bold;
    }

    .flower-address {
      font-size: 30rpx;
      color: rgba(20, 19, 18, 0.45);
      margin: 24rpx 0;
    }

    .btn-wrap {
      display: flex;

      .example {
        padding: 10rpx;
        background: rgba(245, 245, 245, 1);
        color: #000;
        font-size: 24rpx;
        border-radius: 6rpx;
        margin-right: 10rpx;
      }

      .detail {
        padding: 8rpx;
        background: rgba(55, 68, 134, 1);
        color: #fff;
        font-size: 24rpx;
        border-radius: 6rpx;
      }
    }
  }

  .house-img {
    width: 174rpx;
    height: 174rpx;
  }
}

.map-container {
  padding-top: 36rpx;
  height: calc(100vh - 36rpx);
  position: relative;
  background: rgb(252, 252, 252);

  .map {
    width: 100%;
    height: 100%;
  }

  .jumpBtn {
    position: absolute;
  }
}

.hover-btn {
  position: absolute;
  bottom: 316rpx;
  right: 40rpx;
  border-radius: 24rpx;
  width: 104.4rpx;
  height: 104.4rpx;
  background-color: rgba(55, 68, 134, 1);
  text-align: center;
  padding: 4rpx 4rpx 0;
  box-sizing: border-box;
  z-index: 99;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .icon {
    width: 45rpx;
    height: 45rpx;
  }

  .text {
    color: #fff;
    font-size: 18rpx;
  }
}
</style>
